package de.yvert.jingle.tools;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

import de.yvert.jingle.Image;
import de.yvert.jingle.ImageReader;
import de.yvert.jingle.ReaderWriterFactory;
import de.yvert.jingle.hdr.HdrImage2D;
import de.yvert.jingle.impl.writer.ImageWriter_exr;
import de.yvert.jingle.impl.writer.ImageWriter_png;
import de.yvert.jingle.ldr.LdrImage2D;

public class ImageUtils
{

private static final DateFormat TIME_FORMAT = new SimpleDateFormat("yyyy-MM-dd--HH-mm-ss");

public static void writeImage(LdrImage2D image)
{ writeImage(image, TIME_FORMAT.format(new Date())+".png"); }

public static void writeImage(LdrImage2D image, String name)
{
	try
	{
		FileOutputStream fout = new FileOutputStream(name);
		new ImageWriter_png().write(image, fout);
		fout.close();
	}
	catch (IOException e)
	{ e.printStackTrace(); }
}

public static void writeImage(HdrImage2D image)
{ writeImage(image, TIME_FORMAT.format(new Date())+".exr"); }

public static void writeImage(HdrImage2D image, String name)
{
	try
	{
		FileOutputStream fout = new FileOutputStream(name);
		new ImageWriter_exr().write(image, fout);
		fout.close();
	}
	catch (IOException e)
	{ e.printStackTrace(); }
}

public static Image readImageFromRessource(String fname)
{
	try
	{
		InputStream in = ImageUtils.class.getClassLoader().getResourceAsStream(fname);
		if (in == null) throw new NullPointerException(fname);
		int i = fname.lastIndexOf('.');
		String extension = fname.substring(i+1);
		ImageReader reader = ReaderWriterFactory.getReader(extension);
		return reader.load(in);
	}
	catch (IOException e)
	{ throw new RuntimeException(e); }
}

public static Image readImageFromFile(String fname)
{
	try
	{
		InputStream in = new FileInputStream(fname);
		int i = fname.lastIndexOf('.');
		String extension = fname.substring(i+1);
		ImageReader reader = ReaderWriterFactory.getReader(extension);
		return reader.load(in);
	}
	catch (IOException e)
	{ throw new RuntimeException(e); }
}

}
